package com.superlc.ssm.modular.api.controller;

import com.superlc.ssm.common.util.ResponseEntity;
import com.superlc.ssm.common.util.ResponseUtils;
import com.superlc.ssm.core.shiro.util.ShiroKit;
import com.superlc.ssm.modular.sys.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: ssm$
 * @Package: com.superlc.ssm.modular.api.controller$
 * @ClassName: ApiAuthenticationController$
 * @Description: api 远程调用接口认证
 * @Author: super
 * @CreateDate: 2018/8/28$ 16:06$
 * @UpdateUser: 更新者
 * @UpdateDate: 2018/8/28$ 16:06$
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@RestController
@RequestMapping("/api/auth")
public class ApiAuthenticationController {

    @Resource
    private UserInfoService userInfoService;

    @RequestMapping("/login")
    public ResponseEntity login(String username, String password, Boolean rememberMe, HttpServletResponse response){

        if(rememberMe==null){
            rememberMe=false ;
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        Map<String,Object >  responseMap = new HashMap<>();
        //判断是否登陆
        if (ShiroKit.isAuthenticated() ||ShiroKit.getUser()!=null) {
            responseMap.put("sid",subject.getSession().getId());
            responseMap.put("userInfo",subject.getPrincipal());
            response.addCookie(new Cookie("JSESSIONID",(String)subject.getSession().getId() ));
            ResponseEntity  responseEntity = ResponseUtils.success(responseMap);
            responseEntity.setMsg("已经登陆请勿重复登陆！");
            return responseEntity;
        }
        String msg = "";
        try {

            subject.login(token);

            String sid  = (String) subject.getSession().getId();

            responseMap.put("sid",sid);
            responseMap.put("userInfo",subject.getPrincipal());
            // 执行到这里说明用户已登录成功
            return ResponseUtils.success(responseMap);
        } catch (DisabledAccountException e) {
           msg  = "账户已被禁用" ;
        } catch (AuthenticationException e) {
           msg = "用户名或密码错误" ;
        }catch (Exception e){
            msg = e.getMessage();
        }
        return ResponseUtils.failed(msg);
    }
}
